package com.seqb.manage.paper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.ResultVo;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.exception.BdException;
import com.seqb.manage.choice.dao.ChoiceQuestionDao;
import com.seqb.manage.choice.domain.ChoiceQuestionDO;
import com.seqb.manage.dict.service.DictService;
import com.seqb.manage.paper.dao.PaperQuestionDao;
import com.seqb.manage.paper.domain.PaperQuestionDO;
import com.seqb.manage.paper.service.PaperQuestionService;
import com.seqb.manage.synthesis.dao.SynthesisQuestionDao;
import com.seqb.manage.synthesis.domain.SynthesisQuestionDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;

import java.util.Arrays;
import java.util.Map;

/**
 * @author lilinshen
 * @title 试卷试题表
 * @description 请填写相关描述
 * @date 2019-12-04
 */
@Service
public class PaperQuestionServiceImpl implements PaperQuestionService {
    @Autowired
    private DictService dictService;
    @Autowired
    private PaperQuestionDao paperQuestionDao;
    @Autowired
    private ChoiceQuestionDao choiceQuestionDao;
    @Autowired
    private SynthesisQuestionDao synthesisQuestionDao;

    @Override
    public PaperQuestionDO get(Long id) {
        return paperQuestionDao.selectById(id);
    }

    @Override
    public Page<PaperQuestionDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        map.put("isDelete", "0");
        return paperQuestionDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, PaperQuestionDO.class);
        return paperQuestionDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo save(PaperQuestionDO paperQuestion) {
        try {
            Long paperId = paperQuestion.getPaperId();
            String ids = paperQuestion.getIds();
            String type = paperQuestion.getType();
            if (null == paperId || StringUtils.isEmpty(ids) || StringUtils.isEmpty(type)) {
                return ResultVo.error("参数不足");
            }
            StringBuffer msg = new StringBuffer();
            Integer success = 0;
            String[] idArr = ids.split(",");
            for (String questionId : idArr) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("paper_id", paperId);
                queryWrapper.eq("question_id", questionId);
                queryWrapper.eq("type", type);
                PaperQuestionDO exist = paperQuestionDao.selectOne(queryWrapper);
                if (null != exist) {
                    msg.append(questionId).append("、");
                    continue;
                }
                Long sortNumber = 0L;
                queryWrapper = new QueryWrapper();
                queryWrapper.eq("id", questionId);
                if ("1".equals(type)) {
                    ChoiceQuestionDO choiceQuestion = choiceQuestionDao.selectOne(queryWrapper);
                    if (null != choiceQuestion) {
                        sortNumber = choiceQuestion.getSortNumber();
                    }
                } else if ("2".equals(type)) {
                    SynthesisQuestionDO synthesisQuestion = synthesisQuestionDao.selectOne(queryWrapper);
                    if (null != synthesisQuestion) {
                        sortNumber = synthesisQuestion.getSortNumber();
                    }
                }
                PaperQuestionDO save = new PaperQuestionDO();
                save.setPaperId(paperId);
                save.setQuestionId(Long.valueOf(questionId));
                save.setSortNumber(sortNumber);
                save.setType(type);
                int insert = paperQuestionDao.insert(save);
                if (insert <= 0) {
                    throw new BdException("操作失败！");
                }
                success++;
            }
            if (success != idArr.length) {
                msg.deleteCharAt(msg.length() - 1);
                msg.insert(0, "添加" + idArr.length + "条，成功" + success + "条，重复问题id：");
            } else {
                msg.append("添加成功！");
            }
            return ResultVo.ok(msg.toString());
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo update(PaperQuestionDO paperQuestion) {
        try {
            Long id = paperQuestion.getId();
            if (null == id) {
                return ResultVo.error("参数不足！");
            }
            int update = 0;
            String clearField = paperQuestion.getClearField();
            if (StringUtils.isEmpty(clearField)) {
                update = paperQuestionDao.updateById(paperQuestion);
            } else {
                UpdateWrapper updateWrapper = WrapperHandler.genUpdateWrapper(paperQuestion);
                updateWrapper.eq("id", id);
                update = paperQuestionDao.update(paperQuestion, updateWrapper);
            }
            if (update <= 0) {
                throw new BdException("操作失败！");
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

    @Override
    @Transactional
    public int remove(Long id) {
        return paperQuestionDao.deleteById(id);
    }

    @Override
    @Transactional
    public int batchRemove(Long[] ids) {
        return paperQuestionDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public String view(Long id, String type, Model model) {
        try {
            if (StringUtils.isEmpty(type)) {
                return null;
            }
            if ("1".equals(type)) {
                //选择题
                ChoiceQuestionDO choiceQuestion = choiceQuestionDao.selectById(id);
                model.addAttribute("choiceQuestion", choiceQuestion);
                model.addAttribute("choice", dictService.getDictCache("choice_type"));
                return "manage/choice/choiceQuestion.view";
            } else if ("2".equals(type)) {
                //综合题
                SynthesisQuestionDO synthesisQuestion = synthesisQuestionDao.selectById(id);
                model.addAttribute("synthesisQuestion", synthesisQuestion);
                return "manage/synthesis/synthesisQuestion.view";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
